//
//  UWAppDelegate.m
//  Urban Words
//
//  Created by Tim Brandin on 2011-11-18.
//  Copyright (c) 2011 Sypreme. All rights reserved.
//

#import "UWAppDelegate.h"
#import "UWLoginController.h"
#import "UWSettingsController.h"
#import "UWHistoryController.h"
#import "Constants.h"
#import "NSMutableURLRequest+BasicAuth.h"

#define DEBUG_PUSHER    NO

@implementation UWAppDelegate

@synthesize window = _window, tabBarController;
@synthesize facebook, pusher = _pusher;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    // Pusher: Setup connection
    self.pusher = [PTPusher pusherWithKey:PUSHER_API_KEY delegate:self];
    
    // Pusher: We want the connection to automatically reconnect if it dies
    self.pusher.reconnectAutomatically = YES;
    
    // Pusher: Log all events received, regardless of which channel they come from
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePusherEvent:) name:PTPusherEventReceivedNotification object:self.pusher];
    
    // Facebook
    facebook = [[Facebook alloc] initWithAppId:@"244278465627949" andDelegate:self];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"] 
        && [defaults objectForKey:@"FBExpirationDateKey"]) {
        facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
        facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
    }
    
    UINavigationController *gamesNavigation, *friendsNavigation, *searchController;
    
    gamesController = [[UWGamesController alloc] initWithNibName:@"UWGamesController" bundle:nil];
    
    friendController = [[UWFriendsController alloc] initWithNibName:@"UWFriendsController" bundle:nil];
    
    friendsNavigation = [[UINavigationController alloc] initWithRootViewController:friendController];
    friendsNavigation.navigationBar.tintColor = [[UIColor alloc] initWithRed:0.2 green:0.2 blue:0.2 alpha:0];
    [friendsNavigation.navigationBar setBackgroundImage:[UIImage imageNamed:@"uw-navigationbar"] forBarMetrics:UIBarMetricsDefault];
    
    gamesNavigation = [[UINavigationController alloc] initWithRootViewController:gamesController];
    //gamesNavigation.navigationBar.tintColor = [[UIColor alloc] initWithRed:0.8 green:0.8 blue:0.8 alpha:0];
    gamesNavigation.navigationBar.tintColor = [[UIColor alloc] initWithRed:0.2 green:0.2 blue:0.2 alpha:0];
    [gamesNavigation.navigationBar setBackgroundImage:[UIImage imageNamed:@"uw-navigationbar"] forBarMetrics:UIBarMetricsDefault];
    
    searchController = [[UINavigationController alloc] initWithRootViewController:[[[UWHistoryController alloc] initWithNibName:@"UWHistoryController" bundle:nil gameID:@"11"] autorelease]];
    
    self.tabBarController = [[[UITabBarController alloc] init] autorelease];
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:gamesNavigation, friendsNavigation,searchController, nil];

    
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    
    // Check if session is valid, if not -> login
    if (![facebook isSessionValid]) {
        // Go to login screen
        
        UWLoginController *loginController = [[UWLoginController alloc] initWithNibName:@"UWLoginController" bundle:nil];
        loginController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        
        [self.window.rootViewController presentModalViewController:loginController animated:FALSE];
    }
    
    // shake gesture
    application.applicationSupportsShakeToEdit = YES;
    
    [gamesNavigation release];
    [friendsNavigation release];
    
    return YES;
}

- (void)settings {
    UWSettingsController *settingsController = [[UWSettingsController alloc] initWithNibName:@"UWSettingsController" bundle:nil];
    
    UINavigationController *settingsNavigation;
    
    settingsNavigation = [[UINavigationController alloc] initWithRootViewController:settingsController];
    settingsNavigation.navigationBar.tintColor = [[UIColor alloc] initWithRed:0.2 green:0.2 blue:0.2 alpha:0];
    [settingsNavigation.navigationBar setBackgroundImage:[UIImage imageNamed:@"uw-navigationbar"] forBarMetrics:UIBarMetricsDefault];
    
    //settingsController.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    settingsController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    
    [self.window.rootViewController presentModalViewController:settingsNavigation animated:YES];
}

// Pre 4.2 support
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [facebook handleOpenURL:url]; 
}

// For 4.2+ support
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [facebook handleOpenURL:url]; 
}

- (void)fbDidLogin {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
    [defaults synchronize];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setValue:[facebook accessToken] forKey:@"access_token"];
    
    [facebook requestWithGraphPath:@"me" andParams:dict andDelegate:self];
    [self.window.rootViewController dismissModalViewControllerAnimated:YES];
    
    [[UWFriendManager sharedManager] updateFriends];
}

- (void)fbDidLogout {
    
    
    // Go to login screen
    [self.window.rootViewController dismissViewControllerAnimated:YES completion:^{
        
        UWLoginController *loginController = [[UWLoginController alloc] initWithNibName:@"UWLoginController" bundle:nil];
        
        loginController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        
        // Go to login screen
        [self.window.rootViewController presentModalViewController:loginController animated:YES];
    }];
    
    // Remove saved authorization information if it exists
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"]) {
        [defaults removeObjectForKey:@"FBAccessTokenKey"];
        [defaults removeObjectForKey:@"FBExpirationDateKey"];
        [defaults removeObjectForKey:@"Fid"];
        [defaults synchronize];
    }
    
    // Clear databases
    [UWFriendManager.sharedManager clear];
    [UWGamesManager.sharedManager clear];
}

- (void)requestLoading:(FBRequest *)request {
    //NSLog(@"Loading");
}

- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
   // NSLog(@"Response %@", response);
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
   // NSLog(@"Fail: %@", error);
}

- (void)request:(FBRequest *)request didLoad:(id)result {
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[result valueForKey:@"id"] forKey:@"Fid"];
   // NSLog(@"RESULT: %@", [result valueForKey:@"id"]);
    [defaults synchronize];
            
    [[UWGamesManager sharedManager] updateGames];
    
}

- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data {
   // NSLog(@"Raw response");
}

#pragma mark - Event notifications

- (void)handlePusherEvent:(NSNotification *)note
{
    PTPusherEvent *event = [note.userInfo objectForKey:PTPusherEventUserInfoKey];
    NSLog(@"[pusher] Received event %@", event);
}

#pragma mark - PTPusherDelegate methods

- (void)pusher:(PTPusher *)pusher connectionDidConnect:(PTPusherConnection *)connection
{
    if (DEBUG_PUSHER)
        NSLog(@"[pusher-%@] Connected to Pusher (socket id: %@)", pusher.connection.socketID, connection.socketID);
}

- (void)pusher:(PTPusher *)pusher connectionDidDisconnect:(PTPusherConnection *)connection
{
    if (DEBUG_PUSHER)
        NSLog(@"[pusher-%@] Disconnected from Pusher", pusher.connection.socketID);
}

- (void)pusher:(PTPusher *)pusher connection:(PTPusherConnection *)connection failedWithError:(NSError *)error
{
    if (DEBUG_PUSHER)
        NSLog(@"[pusher-%@] Failed to connect to pusher, error: %@", pusher.connection.socketID, error);
}

- (void)pusher:(PTPusher *)pusher connectionWillReconnect:(PTPusherConnection *)connection afterDelay:(NSTimeInterval)delay
{
    if (DEBUG_PUSHER)
        NSLog(@"[pusher-%@] Reconnecting after %d seconds...", pusher.connection.socketID, (int)delay);
}

- (void)pusher:(PTPusher *)pusher didFailToSubscribeToChannel:(PTPusherChannel *)channel withError:(NSError *)error
{
    if (DEBUG_PUSHER)
        NSLog(@"[pusher-%@] Authorization failed for channel %@", pusher.connection.socketID, channel);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)pusher:(PTPusher *)pusher didSubscribeToChannel:(PTPusherChannel *)channel
{
    if (DEBUG_PUSHER)
        NSLog(@"Client %@ subscribed to channel %@.", pusher, channel);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

/* This app uses HTTP basic authentication.
 
 */
- (void)pusher:(PTPusher *)pusher willAuthorizeChannelWithRequest:(NSMutableURLRequest *)request
{
    [request setHTTPBasicAuthUsername:CHANNEL_AUTH_USERNAME password:CHANNEL_AUTH_PASSWORD];
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

- (void)dealloc 
{
    [[NSNotificationCenter defaultCenter] 
     removeObserver:self name:PTPusherEventReceivedNotification object:self.pusher];
    [_pusher release];
    [facebook release];
}


@end
